package servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Pattern;

@WebServlet("/updateBook")
@MultipartConfig(maxRequestSize = 20*1024*1024,maxFileSize=3*1024*1024)
public class BookPhotoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");

        String server_url= "D:\\temp\\files\\";//服务器地址

        try {
            if ("photo".equals(opr)){
                //文件上传
                //取到jsp页面中的file的文件
                Part part =request.getPart("fileField");// <input type="file" name="fileField" id="fileField"/>
                //文件名
                String fileName = part.getSubmittedFileName();

                fileName=getFileName(fileName);

                fileName =server_url.concat(fileName);

                part.write(fileName);

                System.out.println(fileName);


                //按isbn修改数据库的字段 book_photo
                //先按isbn查到一个book对象
                //改掉book的book_photo 值
                //执行更新
                //返回结果
            }
        } catch (IOException exception) {
            exception.printStackTrace();
            out.print(JSON.toJSONString(-1));
        } catch (ServletException e) {
            e.printStackTrace();
        }finally {
            out.flush();
            out.close();
        }


    }
    private static String getFileName(String realFileName) {
        String uuid = UUID.randomUUID().toString();
        uuid =uuid.replace("-","");
        String ext =realFileName;
        ext =ext.substring(ext.lastIndexOf("."));
        return uuid+ext;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
